﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; 
using Newtonsoft.Json;

namespace MyCommon.Middleware
{
    public class ErrorMiddleware
    {
        private readonly RequestDelegate _next;

        public ErrorMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var json = JsonConvert.SerializeObject(new { success = false, msg = exception.Message, code = 500 });
            context.Response.ContentType = "application/json";
            return context.Response.WriteAsync(json);
        }
    }
}
